package com.own.business.system.user.business.service.impl;

import com.own.business.system.user.business.entity.form.GetSensitiveTokenByPhoneForm;
import com.own.business.system.user.business.entity.vo.SensitivePhoneCodeVo;
import com.own.business.system.user.business.property.SensitivePhoneProperty;
import com.own.business.system.user.business.service.SensitivePhoneService;
import com.own.business.system.user.business.service.SystemUserInfoService;
import com.own.component.common.exception.BusinessSimpleException;
import com.own.component.common.util.desensitize.DesensitizeRuleStatic;
import com.own.component.common.util.desensitize.DesensitizeUtil;
import com.own.component.sensitive.check.SensitiveTokenUtil;
import com.own.component.sensitive.check.entity.SensitiveTokenVo;
import com.own.component.sms.core.util.code.SmsCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * SensitivePhoneServiceImpl
 *
 * @author chenxueli
 * @date 2023-11-04 16:17:00
 */
@Slf4j
@Service
public class SensitivePhoneServiceImpl implements SensitivePhoneService {

    @Resource
    private SensitiveTokenUtil sensitiveTokenUtil;

    @Resource
    private SmsCodeUtil smsCodeUtil;
    @Resource
    private SensitivePhoneProperty sensitivePhoneProperty;

    @Resource
    private SystemUserInfoService systemUserInfoService;

    /**
     * 获取敏感信息修改的验证码
     *
     * @param userId 用户id
     * @return 验证码信息
     */
    @Override
    public SensitivePhoneCodeVo getSensitivePhoneCode(Long userId) {
        // 获取用户的手机号
        var info = systemUserInfoService.getByUserId(userId);
        var phone = info.getPhone();
        if (StringUtils.isBlank(phone)) {
            throw new BusinessSimpleException("手机号不存在");
        }
        // 发送验证码
        smsCodeUtil.build(phone, sensitivePhoneProperty, false);
        // 设置返回的手机号信息
        var resultPhone = DesensitizeUtil.build(phone, DesensitizeRuleStatic.PHONE);
        // 封装，返回数据
        return new SensitivePhoneCodeVo(resultPhone);
    }

    /**
     * 根据手机验证码获取敏感信息修改的token
     *
     * @param userId 用户id
     * @param form   敏感信息确认的表单信息
     * @return 修改信息令牌
     */
    @Override
    public SensitiveTokenVo getSensitiveChangeTokenByPhone(Long userId, GetSensitiveTokenByPhoneForm form) {
        return sensitiveTokenUtil.getToken(userId, form.getPublicKey(), () -> {
            // 获取当前登录用户的手机号
            var info = systemUserInfoService.getByUserId(userId);
            var phone = info.getPhone();
            if (StringUtils.isBlank(phone)) {
                throw new BusinessSimpleException("手机号不存在");
            }
            // 发送验证码
            var model = smsCodeUtil.verification(phone, form.getCode());
            if (!model.success()) {
                throw new BusinessSimpleException("验证码不正确");
            }
        });
    }

}
